const Candidate = require('../models/Candidate');
const Department = require('../models/Department');
const { Op } = require('sequelize');

// 查询考生信息
exports.getCandidateInfo = async (req, res) => {
  try {
    const { candidateNumber, idCardNumber } = req.query;

    // 验证查询参数
    if (!candidateNumber && !idCardNumber) {
      return res.status(400).json({
        success: false,
        message: '请提供考生编号或身份证号'
      });
    }

    // 构建查询条件
    const whereClause = {};
    if (candidateNumber) whereClause.candidateNumber = candidateNumber;
    if (idCardNumber) whereClause.idCardNumber = idCardNumber;

    // 查询考生信息
    const candidate = await Candidate.findOne({
      where: whereClause,
      include: [
        {
          model: Department,
          as: 'ApplicationDepartment',
          attributes: ['id', 'name', 'description']
        }
      ],
      attributes: {
        exclude: ['idCardNumber'] // 保护隐私，不返回身份证号
      }
    });

    if (!candidate) {
      return res.status(404).json({
        success: false,
        message: '未找到该考生信息'
      });
    }

    // 格式化录取进度状态描述
    const statusDescriptions = {
      'pending': '待审核',
      'reviewing': '审核中',
      'admitted': '已录取',
      'rejected': '未录取'
    };

    // 构建返回数据
    const result = {
      ...candidate.toJSON(),
      statusDescription: statusDescriptions[candidate.status],
      admissionProgress: getAdmissionProgress(candidate.status)
    };

    return res.status(200).json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('查询考生信息失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，查询考生信息失败',
      error: error.message
    });
  }
};

// 管理员获取考生列表
exports.getCandidateList = async (req, res) => {
  try {
    // 仅管理员可访问
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可查看考生列表'
      });
    }

    const { page = 1, limit = 20, status, departmentId, search } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

    // 构建筛选条件
    if (status) whereClause.status = status;
    if (departmentId) whereClause.applicationDepartmentId = departmentId;
    if (search) {
      whereClause[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { candidateNumber: { [Op.like]: `%${search}%` } },
        { applicationMajor: { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows: candidates } = await Candidate.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: Department,
          as: 'ApplicationDepartment',
          attributes: ['id', 'name']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    // 格式化状态描述
    const statusDescriptions = {
      'pending': '待审核',
      'reviewing': '审核中',
      'admitted': '已录取',
      'rejected': '未录取'
    };

    const formattedCandidates = candidates.map(candidate => ({
      ...candidate.toJSON(),
      statusDescription: statusDescriptions[candidate.status],
      admissionProgress: getAdmissionProgress(candidate.status)
    }));

    return res.status(200).json({
      success: true,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      data: formattedCandidates
    });
  } catch (error) {
    console.error('获取考生列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取考生列表失败',
      error: error.message
    });
  }
};

// 更新考生录取状态
exports.updateCandidateStatus = async (req, res) => {
  try {
    // 仅管理员可操作
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可更新考生状态'
      });
    }

    const { id } = req.params;
    const { status } = req.body;

    if (!status || !['pending', 'reviewing', 'admitted', 'rejected'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的状态值'
      });
    }

    const candidate = await Candidate.findByPk(id);
    if (!candidate) {
      return res.status(404).json({
        success: false,
        message: '未找到该考生信息'
      });
    }

    await candidate.update({ status });

    // 格式化返回数据
    const statusDescriptions = {
      'pending': '待审核',
      'reviewing': '审核中',
      'admitted': '已录取',
      'rejected': '未录取'
    };

    return res.status(200).json({
      success: true,
      message: '考生状态更新成功',
      data: {
        ...candidate.toJSON(),
        statusDescription: statusDescriptions[candidate.status],
        admissionProgress: getAdmissionProgress(candidate.status)
      }
    });
  } catch (error) {
    console.error('更新考生状态失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，更新考生状态失败',
      error: error.message
    });
  }
};

// 计算录取进度百分比
function getAdmissionProgress(status) {
  const progressMap = {
    'pending': 25,
    'reviewing': 50,
    'admitted': 100,
    'rejected': 0
  };
  return progressMap[status] || 0;
};